import React, { useState, useRef } from 'react';
import { Form, Input, Button, Typography, Spin, message, Card, Row, Col, Select } from 'antd';
import { CopyOutlined, DownloadOutlined } from '@ant-design/icons';
import CommonTour, { TourGuideButton } from '@/components/CommonTour';

const { Title, Text } = Typography;
const { TextArea } = Input;

export default function WeiboCopywriting() {
  const [form] = Form.useForm();
  const [isGenerating, setIsGenerating] = useState<boolean>(false);
  const [generatedContent, setGeneratedContent] = useState<string>('');
  const [tourVisible, setTourVisible] = useState(false);

  // 使用HTML元素的ref引用方式
  const topicRef = useRef<HTMLDivElement>(null);
  const styleRef = useRef<HTMLDivElement>(null);
  const audienceRef = useRef<HTMLDivElement>(null);
  const keyPointsRef = useRef<HTMLDivElement>(null);
  const submitRef = useRef<HTMLDivElement>(null);
  const resultRef = useRef<HTMLDivElement>(null);

  const showTour = () => {
    // 延迟显示，确保DOM已经渲染
    setTimeout(() => {
      setTourVisible(true);
    }, 100);
  };

  // 生成微博文案的模拟函数
  const generateContent = (topic: string, keyPoints: string, style: string, targetAudience: string): string => {
    // 这里是模拟生成内容的逻辑，实际应用中应该调用AI模型
    let result = '';

    // 微博风格的开头
    if (style === '活泼幽默') {
      result += "哈哈哈哈，#" + topic + "# 这件事我一定要跟大家分享！🤣 ";
    } else if (style === '专业严谨') {
      result += "关于#" + topic + "#，这里有一些专业分析值得关注：📊 ";
    } else if (style === '温暖治愈') {
      result += "今天想和大家聊聊#" + topic + "#，希望能给你们一点温暖~❤️ ";
    } else if (style === '时尚潮流') {
      result += "OMG！#" + topic + "# 也太潮了吧！简直爱了爱了~✨ ";
    }

    // 核心内容
    if (keyPoints) {
      // 将关键点分割成数组
      const points = keyPoints.split('\n').filter(p => p.trim());

      // 根据风格和目标受众调整内容
      if (targetAudience === '年轻人') {
        result += "姐妹们/兄弟们，重点来啦！👇\n";
        points.forEach((point, index) => {
          result += `💡 ${point}\n`;
        });
      } else if (targetAudience === '职场人士') {
        result += "职场人们请注意这几点！💼\n";
        points.forEach((point, index) => {
          result += `${index + 1}. ${point}\n`;
        });
      } else if (targetAudience === '宝妈') {
        result += "宝妈们看过来！这些太实用了~👶\n";
        points.forEach((point, index) => {
          result += `⭐ ${point}\n`;
        });
      } else {
        points.forEach((point, index) => {
          result += `👉 ${point}\n`;
        });
      }
    } else {
      // 如果没有提供关键点，生成默认内容
      if (targetAudience === '年轻人') {
        result += "姐妹们/兄弟们，这个真的绝了！我已经亲测有效~\n";
        result += "1. 首先一定要注意这一点！\n";
        result += "2. 然后你需要这样做...\n";
        result += "3. 最后别忘了这个小技巧！\n";
      } else if (targetAudience === '职场人士') {
        result += "作为过来人，给大家几点实用建议：\n";
        result += "💼 工作中一定要注意这些细节\n";
        result += "📈 如何提高工作效率的小技巧\n";
        result += "🤝 职场人际关系处理指南\n";
      } else if (targetAudience === '宝妈') {
        result += "带娃路上总结的血泪经验：\n";
        result += "👶 宝宝饮食注意事项\n";
        result += "🛁 如何让宝宝爱上洗澡\n";
        result += "😴 宝宝睡眠问题全解决\n";
      } else {
        result += "这个真的太有用了！分享给大家：\n";
        result += "⭐ 第一点超重要\n";
        result += "🔥 第二点很多人都不知道\n";
        result += "💯 第三点亲测有效\n";
      }
    }

    // 根据风格添加结尾
    if (style === '活泼幽默') {
      result += "大家觉得怎么样？快来评论区聊聊吧~😂 #" + topic + "#\n";
    } else if (style === '专业严谨') {
      result += "以上是我的专业分析，希望对大家有所帮助。如有不同意见，欢迎在评论区探讨。#" + topic + "#\n";
    } else if (style === '温暖治愈') {
      result += "希望这些能给你们带来一点温暖~记得分享给需要的朋友哦~💕 #" + topic + "#\n";
    } else if (style === '时尚潮流') {
      result += "这么潮的东西必须分享给你们！赶紧get起来~💅 #" + topic + "#\n";
    }

    // 微博标签和@功能（模拟）
    result += "\n#热门话题# #生活技巧#\n";
    result += "@微博小助手 @时尚达人 @生活薯";

    return result;
  };

  // 处理表单提交
  const handleSubmit = async (values: any) => {
    try {
      setIsGenerating(true);
      const { topic, keyPoints, style, targetAudience } = values;

      // 模拟API请求延迟
      await new Promise(resolve => setTimeout(resolve, 1500));

      const generated = generateContent(topic, keyPoints, style, targetAudience);
      setGeneratedContent(generated);
      message.success('微博文案生成成功！');
    } catch (error) {
      message.error('生成失败，请稍后重试');
    } finally {
      setIsGenerating(false);
    }
  };

  // 复制生成的内容
  const handleCopy = () => {
    navigator.clipboard.writeText(generatedContent).then(() => {
      message.success('内容已复制到剪贴板');
    }).catch(() => {
      message.error('复制失败');
    });
  };

  // 下载生成的内容
  const handleDownload = () => {
    const blob = new Blob([generatedContent], { type: 'text/plain;charset=utf-8' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = '微博文案.txt';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(link.href);
    message.success('文件下载成功');
  };

  // 定义引导步骤
  const tourSteps = [
    {
      key: 'topic',
      title: '输入微博主题',
      description: '请输入微博文案的主题',
    },
    {
      key: 'style',
      title: '选择文案风格',
      description: '选择您想要的微博文案风格，如活泼幽默、专业严谨等',
    },
    {
      key: 'audience',
      title: '选择目标受众',
      description: '选择微博内容的目标受众，如年轻人、职场人士等',
    },
    {
      key: 'keyPoints',
      title: '输入核心要点（可选）',
      description: '请输入微博的核心要点，每行一个要点，如不填写将自动生成',
    },
    {
      key: 'submit',
      title: '生成微博文案',
      description: '点击按钮生成符合微博平台的文案',
    },
    {
      key: 'result',
      title: '查看生成结果',
      description: '生成成功后，您可以在此处查看、复制或下载生成的文案',
    },
  ];

  // 组织ref引用
  const tourRefs = {
    topic: topicRef,
    style: styleRef,
    audience: audienceRef,
    keyPoints: keyPointsRef,
    submit: submitRef,
    result: resultRef,
  };

  // 风格选项
  const styleOptions = [
    { label: '活泼幽默', value: '活泼幽默' },
    { label: '专业严谨', value: '专业严谨' },
    { label: '温暖治愈', value: '温暖治愈' },
    { label: '时尚潮流', value: '时尚潮流' },
  ];

  // 目标受众选项
  const audienceOptions = [
    { label: '年轻人', value: '年轻人' },
    { label: '职场人士', value: '职场人士' },
    { label: '宝妈', value: '宝妈' },
    { label: '大众', value: '大众' },
  ];

  return (
    <>
      <div style={{ padding: '24px' }}>
        <div style={{ marginBottom: 24 }}>
          <Title level={2} style={{ display: 'flex', alignItems: 'center', marginBottom: 8 }}>
            微博文案生成
            <TourGuideButton onClick={showTour} />
          </Title>
        </div>
        <Card style={{ marginBottom: '24px' }}>
          <Form
            form={form}
            layout="vertical"
            onFinish={handleSubmit}
            initialValues={{
              style: '活泼幽默',
              targetAudience: '年轻人',
            }}
          >
            <Row gutter={[16, 16]}>
              <Col xs={24} md={12}>
                <Form.Item
                  name="topic"
                  label="微博主题"
                  rules={[{ required: true, message: '请输入微博主题' }]}
                >
                  <div ref={topicRef}>
                    <Input placeholder="请输入微博主题" />
                  </div>
                </Form.Item>
              </Col>
              <Col xs={24} md={12}>
                <Form.Item
                  name="style"
                  label="文案风格"
                  rules={[{ required: true, message: '请选择文案风格' }]}
                >
                  <div ref={styleRef}>
                    <Select placeholder="请选择文案风格" options={styleOptions} />
                  </div>
                </Form.Item>
              </Col>
              <Col xs={24} md={12}>
                <Form.Item
                  name="targetAudience"
                  label="目标受众"
                  rules={[{ required: true, message: '请选择目标受众' }]}
                >
                  <div ref={audienceRef}>
                    <Select placeholder="请选择目标受众" options={audienceOptions} />
                  </div>
                </Form.Item>
              </Col>
              <Col xs={24}>
                <Form.Item
                  name="keyPoints"
                  label="核心要点（可选）"
                >
                  <div ref={keyPointsRef}>
                    <TextArea rows={4} placeholder="请输入微博的核心要点，每行一个要点，如不填写将自动生成" />
                  </div>
                </Form.Item>
              </Col>
              <Col xs={24}>
                <Form.Item>
                  <div ref={submitRef}>
                    <Button type="primary" htmlType="submit" loading={isGenerating} style={{ width: '100%' }}>
                      {isGenerating ? <Spin /> : '生成微博文案'}
                    </Button>
                  </div>
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </Card>

        {generatedContent && (
          <Card title="生成结果" extra={
            <div style={{ display: 'flex', gap: '8px' }}>
              <Button icon={<CopyOutlined />} onClick={handleCopy}>复制</Button>
              <Button icon={<DownloadOutlined />} onClick={handleDownload}>下载</Button>
            </div>
          }>
            <div ref={resultRef} style={{ whiteSpace: 'pre-wrap', wordBreak: 'break-word', lineHeight: 1.6 }}>
              {generatedContent}
            </div>
          </Card>
        )}
      </div>

      <CommonTour
        open={tourVisible}
        onClose={() => setTourVisible(false)}
        steps={tourSteps}
        targetRefs={tourRefs}
      />
    </>
  );
}